package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    // 处理查询所有部门请求
    @RequestMapping("/list")
    @RequiresPermissions(value = {"role:list", "角色列表"}, logical = Logical.OR)
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "role/list";  // 找视图 /WEB-INF/views/department/list.jsp
    }

    // 处理删除所有部门请求
    @RequestMapping("/delete")
    @RequiresPermissions(value = {"role:delete", "角色删除"}, logical = Logical.OR)
    @ResponseBody
    public JSONResult delete(Long id) {
        System.out.println("delete");
        System.out.println("id" + id);
        try {
            if (id != null) {
                // 传id值就删除对应的部门
                roleService.delete(id);
            }
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, "操作失败, 请联系管理员");
        }

    }

    // 处理去新增的请求 http://localhost/department/input.do
    @RequestMapping("/input")
    @RequiresPermissions(value = {"role:input", "角色编辑"}, logical = Logical.OR)
    public String input(Long id, Model model) {

        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("allPermissions", permissions);
        // 传id 去修改
        if (id != null) {
            model.addAttribute("role", roleService.get(id));
            return "role/input";
        }
        // 无id 去新增
        return "role/input";  // 找视图 /WEB-INF/views/department/input.jsp
    }

    // 处理新增或修改请求 http://localhost/department/saveOrUpdate.do
    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"role:saveOrUpdate", "角色新增/修改"}, logical = Logical.OR)
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() != null) {
            roleService.update(role, ids);
        } else {
            roleService.save(role, ids);
        }
        return "redirect:/role/list.do";
    }
}


